package com.uduew.sjd.ui.agreement

import android.content.Intent
import com.uduew.sjd.BR
import com.uduew.sjd.MainActivity
import com.uduew.sjd.R
import com.uduew.sjd.config.Const
import com.uduew.sjd.ui.base.BaseActivity
import com.uduew.sjd.ui.base.StateHolder
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.kunminx.architecture.ui.page.DataBindingConfig
import com.kunminx.architecture.ui.state.State
import com.uduew.sjd.config.AppConfig

class PermissionActivity : BaseActivity() {
    private lateinit var mStates: PrivacyStates

    override fun initViewModel() {
        mStates = getActivityScopeViewModel(PrivacyStates::class.java)
    }

    override fun getDataBindingConfig(): DataBindingConfig? {
        return DataBindingConfig(R.layout.fragment_permission, BR.vm, mStates)
            .addBindingParam(
                BR.click,
                ClickProxy()
            )
    }

    private fun gotoMain() {
        AppConfig.mConfigs.isPermission.set(true)
        this@PermissionActivity.startActivity(
            Intent(
                this@PermissionActivity,
                MainActivity::class.java
            )
        )
        finish()
    }

    open inner class ClickProxy {

        fun disagree() {
            finish()
        }

        fun agreement() {


            XXPermissions.with(this@PermissionActivity)
                .permission(
                    Permission.CAMERA,
                    Permission.READ_SMS,
                    Permission.GET_INSTALLED_APPS,
                    Permission.ACCESS_COARSE_LOCATION,
                    Permission.READ_PHONE_STATE
                )
                .request(object : OnPermissionCallback {
                    override fun onGranted(
                        permissions: List<String?>,
                        allGranted: Boolean
                    ) {
                        if (!allGranted) {
                            gotoMain()
                            return
                        }
                        gotoMain()
                    }
                })
        }


    }

    class PrivacyStates : StateHolder() {
        val agreementChecked: State<Boolean> = State(true)
        val url: State<String> = State(Const.PERMISSION_URL)
    }
}